#include "server.h"
#include <stdio.h>
server::server()
{
		// create message queue
		messQ = CreateMessageQ(KEY_MSG);
		if (messQ == INVALID_HANDLE){
			printf("Eroare la Creare Mailslot");
			exit(1);
		}

		// create semaphore for protecting the shared memory zone
		sem = CreateSem(KEY_SEM,1,1);
		if (sem == INVALID_HANDLE){
			printf("Eroare la Creare semafor");
			exit(1);
		}
		// create semaphore for the operations syncronizing 
		semOp = CreateSem(KEY_SEM2,0,1);
		if (semOp == INVALID_HANDLE){
			printf("Eroare la Creare semafor");
			exit(1);
		}

		// create mapping for the shared memory
		sh = CreateSharedMemory(KEY_SHM,4096);
		if (sh == INVALID_HANDLE){
			printf("Eroare la Creare sharedMemory");
			exit(1);
		}
		Node * arb = (Node*)AttachSharedMemory (sh);
		if (arb == NULL){// eroare
					printf("Eroare a MapViewOfFILe");
					exit(1);
		}
		bt.setArbMemory(arb); 	
}


server::~server()
{
		CloseMessageQueue(messQ);
		CloseSem(sem);
		CloseSem(semOp);
		CloseSharedMemory(sh);
}


void server::run()
{
	tMsg message;	// received message
	BOOL bRes;
	byte finished = 0; // exit message received

	while (!finished)
	{
			bRes = ReceiveMessageQueue (messQ, &message);
			if (!bRes){
				printf("Could not receive");
				exit(1);
			}
			switch (message.type){
				case (MSG_EXIT):
					finished = 1; 
					break;
				
				case (MSG_ADD): 
					AcquireSem(sem);
					bt.addNode(message.value); 
					ReleaseSem(sem);
					break;
					
				case (MSG_REMOVE): 
					AcquireSem(sem);
					bt.Delete(message.value,0);
					ReleaseSem(sem);
					break;
				
				case (MSG_CLEAR):
					AcquireSem(sem);
					bt.Clear();		
					ReleaseSem(sem);
					break;
					
				case (MSG_PRINT):
					ReleaseSem(semOp);
		}

}
}
int main()
{
	server s;
	s.run();
}